package org.apache.shiro;

import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.SimpleAccountRealm;
import org.apache.shiro.subject.Subject;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

/**
 * @author fangtongle
 * @version 1.0
 * @description Shiro认证
 * @date 2018/4/19
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class shiro_01 {

    SimpleAccountRealm simpleAccountRealm = new SimpleAccountRealm();

    @Before
    public void add() {
        simpleAccountRealm.addAccount("tl", "123");
    }

    // Shiro认证
    @Test
    public void contextLoads() {
        // 1. 构建SecurityManager环境
        DefaultSecurityManager securityManager = new DefaultSecurityManager();
        securityManager.setRealm(simpleAccountRealm);

        // 2. 主体来提交认证请求
        SecurityUtils.setSecurityManager(securityManager);
        Subject subject = SecurityUtils.getSubject();

        UsernamePasswordToken token = new UsernamePasswordToken("tl", "123");
        subject.login(token);

        System.out.println("isAuthenticated: " + subject.isAuthenticated());

        subject.logout();
        System.out.println("isAuthenticated: " + subject.isAuthenticated());
    }

}
